<?php
namespace Admin\Model;
use Think\Model;

class ContractModel extends AbstractModel {

    public $_validate = array(
        array('Title','require','请输入合同名称',Model::MUST_VALIDATE),
        array('SPID','require','请选择乙方',Model::MUST_VALIDATE),
        array('FPID','require','请选择甲方',Model::MUST_VALIDATE)
    );

    //获取合同列表
    public function MyshowList(){
        $userInfo=session();
        $username=$userInfo['USER']['TrueName'];
        $userID=$userInfo['USER_ID'];

        $where = " isDel!=1 AND userID=".$userID;
        $user=D('user');
        $Department=D('Department');
        $keyword = I('keyword');
        if(!empty($keyword)){
            $where .= " AND Title like '%$keyword%' ";
        }
        $return = array();
        $sql = " SELECT COUNT(*) AS count  FROM contract WHERE $where ";
        $count = $this->query($sql);
        $count = $count[0]['count'];

        $page = $this->Mypage($count, 8);
        $sql = "SELECT ID,ProjectID,CNO,Title,InOutType,ContractType,FPID,SPID,Bill,UserID,LeaderUserID,DepID FROM contract WHERE $where ORDER BY AddTime DESC LIMIT  $page->firstRow , $page->listRows";
        $res = $this->query($sql);
        foreach ($res as $key => $value) {
           

            $ContractType=$this->query("SELECT Name FROM datadict WHERE ParentID=43 AND ConfigValue=".$value['ContractType']);
            $value['ContractType']=$ContractType['0']['Name'];
           // var_dump($value['InOutType']);
            // 付钱
            if($value['InOutType']==1){
                $jfsql="SELECT ID,`Name` FROM  department  WHERE ID='".$value['FPID']."'";
                $ycsql="SELECT ID,`Name` FROM  customer  WHERE ID='".$value['SPID']."'";
            }else{
            //收钱
                $jfsql="SELECT ID,`Name` FROM  customer  WHERE ID='".$value['FPID']."'";
                $ycsql="SELECT ID,`Name` FROM  department  WHERE ID='".$value['SPID']."'";
            }

            $FirstParty=$this->query($jfsql);
            $SecondParty=$this->query($ycsql);

            $UserName=$user->field("UserName AS UserName")->where(array('ID' =>$value['UserID']))->find();
            $LeaderName=$user->field("UserName AS LeaderName")->where(array('ID' =>$value['LeaderUserID']))->find();
            $DepName=$Department->field("Name AS DepName")->where(array('ID' =>$value['DepID']))->find();
            $value['UserID']=$UserName['UserName'];
            $value['LeaderUserID']=$LeaderName['LeaderName'];
            $value['DepID']=$DepName['DepName'];


            //甲方和乙方
            $value['FPID']=$FirstParty[0]['Name'];
            $value['SPID']=$SecondParty[0]['Name'];

            $value['InOutType']=($value['InOutType']==0)?'收入合同':'支出合同';
            $arr[]=$value;
        }
        $return['list'] = $arr;
        
        $return['page'] = $page->show('Admin');
        return $return;
    }

    //生成合同编号
    public function getNowNO(){
        if(I("ID")!=''){
            $date = date("ym");
            $serialno = D('serialno');
            $sql = "SELECT NowNO FROM serialno WHERE Name = 'project' AND NowNO LIKE '%{$date}%' ORDER BY ID DESC";
            $res = $serialno->query($sql);
            if(!empty($res)){
                $nowNo = $res[0]['NowNO'] + 1;
            }else{
                $nowNo = date('ymd')."01";
            }
            $data['Name'] = 'project';
            $data['NowNO'] = $nowNo; 
            $id = $serialno->add($data);
            return $nowNo;
         }
    }
    
    // 合同收入支出类型
    public function InOutType(){
        $array[]=array('ID'=>'0','Name'=>'收入合同');
        $array[]=array('ID'=>'1','Name'=>'支出合同');
        return $array;
    }

    //合同相关方类型
    public function ContractPartner(){
        $array[]=array('ID'=>1,'Name'=>'乙方联合单位');
        $array[]=array('ID'=>2,'Name'=>'多方');
        $array[]=array('ID'=>3,'Name'=>'设计单位');
        $array[]=array('ID'=>4,'Name'=>'监理单位');
        $array[]=array('ID'=>5,'Name'=>'测评单位');
        $array[]=array('ID'=>6,'Name'=>'审计单位');
        $array[]=array('ID'=>7,'Name'=>'上级主管部门');
        return $array;

    }

    // 合同类型
    public function ContractType(){
        $DataDict=D('datadict');
        // 分类在数据字典中添加
        $sql="SELECT ConfigValue AS ID,`Name` AS `Name` FROM datadict WHERE ParentID = '43'";
        $res=$DataDict->query($sql);
        return $res;

    }

    // 合同分级
    public function ContractLevel(){
        $DataDict=D('datadict');
        // 分类在数据字典中添加
        $sql="SELECT ConfigValue AS ID,`Name` AS `Name` FROM datadict WHERE ParentID = '46'";
        $res=$DataDict->query($sql);
        return $res;

    }
    public function Myshow($ID){
        $sql1="SELECT * FROM contract WHERE ID='".$ID."'";
        $result=$this->query($sql1);
        $user=D('user');
        $Department=D('Department');
        $Project=D('Project');
        $ProjectName=$Project->field("Name AS Name")->where(array('ID' =>$result[0]['ProjectID']))->find();
        $UserName=$user->field("UserName AS UserName")->where(array('ID' =>$result[0]['UserID']))->find();
        $LeaderName=$user->field("UserName AS LeaderName")->where(array('ID' =>$result[0]['LeaderUserID']))->find();
        $DepName=$Department->field("Name AS DepName")->where(array('ID' =>$result[0]['DepID']))->find();
        $sql2="SELECT A.ID,A.ContractID,A.PartnerType,A.CPID,B.`Name` FROM contractpartner A LEFT JOIN customer B ON(A.CPID=B.ID) WHERE ContractID='$ID'";
        $contractpartner=$this->query($sql2);
        $ContractPartnertype=$this->ContractPartner();
        foreach ($contractpartner as $key => $value) {
            foreach ($ContractPartnertype as $key => $value2) {
                if($value2['ID']==$value['PartnerType']){
                    $value['CPIDName']=$value2['Name'];
                }
            }
            $Cparray[]=$value;
        }
        // 付钱
        if($result[0]['InOutType']==1){
            $jfsql="SELECT ID,`Name` FROM  department  WHERE ID='".$result[0]['FPID']."'";
            $ycsql="SELECT ID,`Name` FROM  customer  WHERE ID='".$result[0]['SPID']."'";
        }else{
        //收钱
            $jfsql="SELECT ID,`Name` FROM  customer  WHERE ID='".$result[0]['FPID']."'";
            $ycsql="SELECT ID,`Name` FROM  department  WHERE ID='".$result[0]['SPID']."'";
        }
        $FirstParty=$this->query($jfsql);
        $SecondParty=$this->query($ycsql);
        $result[0]['ContractPartner']=$Cparray;
        $result[0]['UserName']=$UserName['UserName'];
        $result[0]['LeaderName']=$LeaderName['LeaderName'];
        $result[0]['DepName']=$DepName['DepName'];
        $result[0]['ProjectName']=$ProjectName['Name'];

        //甲方和乙方
        $result[0]['FPID']=$FirstParty[0]['ID'];
        $result[0]['SPID']=$SecondParty[0]['ID'];
        $result[0]['FPIDName']=$FirstParty[0]['Name'];
        $result[0]['SPIDName']=$SecondParty[0]['Name'];
        //var_dump($result);
        return $result[0];
    }



       public function Customershow(){
        $Customer=D('customer');
        $where = "";
        $keyword = I('keyword');
        if(!empty($keyword)){
            $where['Name|Contact|Address|Phone'] = array('like','%'.$keyword.'%');
        }
        $where['IsDel'] = 0;
        $return = array();
        $count = $Customer->where($where)->count();
        $page = $Customer->Mypage($count, 8);
        $fields = "a.*";
        $join = "";
        $res = $Customer->alias('a')->join($join)->where($where)->field($fields)->limit($page->firstRow.','.$page->listRows)->select();
        $return['list'] = $res;
        $return['page'] = $page->show('Admin');
        return $return;
    
    }


    public function Myupdata($result){
        //开始事物
        $result=(int)I('ID'); 
        $this->startTrans();
        if(!$this->create()){
            $results['msg'] = $this->getError();
            $results['state'] = 0;
        }else{
            $ContractPartner=D('contractpartner');
            if($_POST['ContractPartnerList']){
                $ContractPartnerList=$_POST['ContractPartnerList'];
                    foreach ($ContractPartnerList as $key => $value) {
                        $Contractdata[]=json_decode($value,true);
                    }
                    foreach ($Contractdata as $key => $value) {
                        $value['ContractID']=$result;
                        $value['addTime']=$_POST['AddTime'];
                        $addiddata[]=$value;
                    }
                    $ContractPartner->where('ContractID='.$result)->delete();
                    $result2=$ContractPartner->addAll($addiddata);
                }else{
                    $ContractPartner->where('ContractID='.$result)->delete();
            }
            $res = $this->save();
            if($res) {
                $this->commit();
                $results['status'] = 1;
                $results['msg'] = "修改成功！";
                $results['id'] = $res;
            }else{
                $this->Form->rollback();
                $results['status'] = 0;
                $results['msg'] = "修改错误！";
            }

        }
        
        return $results;
    }

       /**
     * 删除业务
     */
    public function MydeletP(){
        $dbName = $this->getTableName();
        $ID = I("ID");
        $sql = " UPDATE {$dbName} SET IsDel = 1 WHERE ID = {$ID}";
        $res = $this->execute($sql);
        if($res){
            $results['state'] = 1;
            $results['msg'] = "删除成功！";
            $results['id'] = $res;
        }else{
            $results['state'] = 0;
            $results['msg'] = "删除错误！";
        }
        return $results;
    }


            //pdf 打水印预览
    public function pdf($ID){
        //获取水印和电子水印
        $StampSrc=$this->query("SELECT B.ImgUrl FROM contractbody AS A LEFT JOIN stamp AS B ON(A.StampID=B.ID) WHERE A.ContractID=".$ID);
        $WarterMarkSrc=$this->query("SELECT B.ImgUrl FROM contractbody AS A LEFT JOIN watermark AS B ON(A.WMID=B.ID) WHERE A.ContractID=".$ID);
        //var_dump($WarterMarkSrc['0']['ImgUrl']);  exit();        
        Vendor('mpdf.mpdf');
        $mpdf=new \mPDF('utf-8','A4','','',25,25,16,16);
        //html内容
        //字段含义按顺序分别为：  
        //$mode,$format,默认字体大小，默认字体，左页边距25（默认），右页边距（25），上页边距16，下页边距16，mgh:16,mgf:13,o
        //设置字体，解决中文乱码  
        $mpdf -> useAdobeCJK = TRUE;  
        $mpdf ->autoScriptToLang = true;  
        $mpdf -> autoLangToFont = true;  
        //$mpdf-> showImageErrors = true; //显示图片无法加载的原因，用于调试，注意的是,我的机子上gif格式的图片无法加载出来。  
        //设置pdf显示方式  
        $mpdf->SetDisplayMode('fullpage');  
        //水印
   /*     $mpdf->SetWatermarkText('云上贵州复印无效',0.2);
        $mpdf->showWatermarkText=true;
        $mpdf->watermark_font = 'GB';*/

        if($WarterMarkSrc['0']['ImgUrl']!=NULL){
            //var_dump($WarterMarkSrc['0']); exit();
            $mpdf->SetWatermarkImage($WarterMarkSrc['0']['ImgUrl'], 0.2, '', array(80,120));
            $mpdf->showWatermarkImage = true;
        }

        if($StampSrc['0']['ImgUrl']!=NULL){
            $mpdf->SetWatermarkImage($StampSrc['0']['ImgUrl'], 0.2, '', array(80,120));
            $mpdf->showWatermarkImage = true;
        }
      
        
        //目录相关设置：  
        //Remember bookmark levels start at 0(does not work inside tables)H1 - H6 must be uppercase  
        //$this->h2bookmarks = array('H1'=>0, 'H2'=>1, 'H3'=>2);  


        $mpdf->h2toc = array('H3'=>0,'H4'=>1,'H5'=>2);  
        $mpdf->h2bookmarks = array('H3'=>0,'H4'=>1,'H5'=>2);  
        $mpdf->mirrorMargins = 1;  
        //是否缩进列表的第一级  
        $mpdf->list_indent_first_level = 0;  
          
        //导入外部css文件：  
        /*$stylesheet1 = file_get_contents(CSS_PATH.'target.css');  
        $mpdf->WriteHTML($stylesheet1,1);  */
        ///index.php?m=Admin&c=Contract&a=view&ContractID=16
        $url =  'http://'.$_SERVER['HTTP_HOST'].U('Admin/Contract/view',array('ContractID'=>$ID));
        $html = file_get_contents($url); 

        $mpdf->WriteHTML($html);  //$html中的内容即为变成pdf格式的html内容。  
        $fileName = '合同.pdf';  
        //输出pdf文件  
        $mpdf->Output($fileName,'I'); //'I'表示在线展示 'D'则显示下载窗口  
        exit; 
    }

}